package cn.codeforfun;

import cn.codeforfun.utils.MavenUtils;
import cn.codeforfun.utils.__;
import cn.hutool.core.util.ObjectUtil;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 初始化项目
 */
@Mojo(name = "initial", defaultPhase = LifecyclePhase.COMPILE)
public class MojoInitial extends AbstractMojo {
    @Parameter(defaultValue = "${project}", required = true, readonly = true)
    MavenProject project;

    @Override
    public void execute() {
        List<Dependency> dependencies = project.getOriginalModel().getDependencies();
        File basedir = project.getBasedir();
        try {
            // 添加常用依赖
            addDependencies(dependencies);
            FileWriter fileWriter = new FileWriter(basedir.getAbsolutePath() + File.separator + "pom.xml");
            project.writeOriginalModel(fileWriter);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void addDependencies(List<Dependency> dependencies) throws XmlPullParserException, IOException {
        MavenProject resolveResult = MavenUtils.resolvePom("template/template.pom.xml");
        List<Dependency> dependencies1 = resolveResult.getDependencies();
        if (ObjectUtil.isEmpty(dependencies1)) {
            return;
        }
        for (Dependency dependency : dependencies1) {
            int index = __.findIndex(dependencies, s -> dependency.getGroupId().equals(s.getGroupId()) &&
                    dependency.getArtifactId().equals(s.getArtifactId()));
            if (index == -1) {
                dependencies.add(dependency);
            } else {
                dependencies.set(index, dependency);
            }
        }
    }
}
